package com.fastCms.business.frame.utils;

import com.aliyun.oss.OSSClient;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import static com.fastCms.business.frame.utils.EncryptionUtil.stringMd5;


/**
 * @author : iron
 * @version : 1.0.0
 * @date : 10:04 2019-05-28
 */
@Slf4j
public class OssUtil {

    public static final String ALIYUN_OSS_ENDPOINT = "oss-cn-hongkong.aliyuncs.com";
    public static final String ALIYUN_OSS_ACCESSKEYID = "LTAIZU2uk2u1v1l5";
    public static final String ALIYUN_OSS_ACCESSKEYSECRET = "FkaPIo4nJM5RJJpMbCgBjBUYpaIo0P";
    public static final String ALIYUN_OSS_BUCKET = "ruida";
    public static final String ALIYUN_OSS_URL = "ruida.oss-cn-hongkong.aliyuncs.com/";


    public static final String UploadFile(String filename, File file) {
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = ALIYUN_OSS_ENDPOINT;
        try {
            // 创建OSSClient实例。
            OSSClient ossClient = new OSSClient(ALIYUN_OSS_ENDPOINT, ALIYUN_OSS_ACCESSKEYID, ALIYUN_OSS_ACCESSKEYSECRET);
            InputStream is = new FileInputStream(file);

            String postfix = getpostfix(filename);
            filename = stringMd5(filename).substring(0, 5) + System.currentTimeMillis() + postfix;
            ossClient.putObject(ALIYUN_OSS_BUCKET, filename, is);
            // 关闭OSSClient。
            ossClient.shutdown();
        } catch (FileNotFoundException e) {
            log.error("upload error {}", e);
        }
        log.info("file url :{}", ALIYUN_OSS_URL + filename);
        return ALIYUN_OSS_URL + filename;
    }


    public static void main(String[] args) {
        System.out.println(UploadFile("1.png", new File("/Users/zheng/soft/img/1.png")));
    }

    public static String getpostfix(String fname) {
        String postfix = null;
        if (fname == null) {
            return "";
        }
        if (fname.indexOf(".") != -1) {
            postfix = fname.substring(fname.indexOf("."));
        } else {
            return "非法文件名";
        }
        return postfix;
    }
}
